package com.hr.ping.util;

import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@Component
public class FileLockUtil {

    private final Path lockFilePath = Paths.get("rate_limit.lock");

    public Mono<FileLock>  acquireRateLimitLock() {
        try (FileChannel channel = FileChannel.open(lockFilePath, StandardOpenOption.CREATE,
                                                    StandardOpenOption.WRITE)) {
            FileLock lock = channel.tryLock();
            if (lock != null) {
                return Mono.just(lock);
            } else {
                throw new RuntimeException("Rate limited");
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to acquire lock", e);
        }
    }
}
